//
//  PublushGoodsViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/10.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "PublushGoodsViewController.h"

#import "AddImgButton.h"

@interface PublushGoodsViewController ()<UITableViewDelegate, UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UITextFieldDelegate,CTAssetsPickerControllerDelegate,UINavigationBarDelegate,UITextViewDelegate>

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) NSMutableArray<UIImage *> *mainImageArray;
@property (nonatomic, strong) NSMutableArray<UIImage *> *detailImageArray;
@property (nonatomic, strong) NSMutableArray<NSString *> *mainUrlArray;
@property (nonatomic, strong) NSMutableArray<NSString *> *detailUrlArray;

@property (nonatomic,strong)  ThemeButton  *button;

@property (nonatomic,strong)  UITextField    *titleField;
@property (nonatomic,strong)  UITextField    *valueField;
@property (nonatomic,strong)  UITextView     *detailView;

@property (nonatomic,assign)  BOOL            isMainPic;
@property (nonatomic,assign)  NSInteger       imageCount;

@property (nonatomic,copy)    NSString     * mainImageUrl;
@property (nonatomic,copy)    NSString     * mainImageFirstUrl;
@property (nonatomic,copy)    NSString     * detailImageUrl;


@end

@implementation PublushGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"发布商品";
    
    self.mainUrlArray = [NSMutableArray array];
    self.detailUrlArray = [NSMutableArray array];
    
    self.mainImageArray = [NSMutableArray array];
    self.detailImageArray = [NSMutableArray array];
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:self.tableView];
    
    if (_shopGoodsDetailModel) {
        for (int i = 0; i < _shopGoodsDetailModel.mian_pics.count; i++) {
            ShopGoodsMainPicsModel *mainPicsModel = _shopGoodsDetailModel.mian_pics[i];
            UIImageView *imageView = [[UIImageView alloc] init];
            [imageView sd_setImageWithURL:[NSURL URLWithString:mainPicsModel.pic] placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                [self.mainImageArray addObject:image];
                if (self.mainImageArray.count == self.shopGoodsDetailModel.mian_pics.count) {
                    [self reload];
                }
            }];
        }
        for (int i = 0; i < _shopGoodsDetailModel.detail_pics.count; i++) {
            ShopGoodsDetailPicsModel *detailPicsModel = _shopGoodsDetailModel.detail_pics[i];
            UIImageView *imageView = [[UIImageView alloc] init];
            [imageView sd_setImageWithURL:[NSURL URLWithString:detailPicsModel.pic] placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                [self.detailImageArray addObject:image];
                if (self.detailImageArray.count == self.shopGoodsDetailModel.detail_pics.count) {
                    [self reloadDetail];
                }
            }];
        }
    }
    
    _isMainPic = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

-(void)mainPicAdd
{
    _isMainPic = YES;
    self.imageCount = 9 - self.mainImageArray.count;
    if (self.imageCount == 0) {
        return;
    }
    [self alterIconPortrait];
}

-(void)detailPicAdd
{
    _isMainPic = NO;
    self.imageCount = 9 - self.detailImageArray.count;
    if (self.imageCount == 0) {
        return;
    }
    [self alterIconPortrait];
}

-(void)surePublic
{
    if (self.titleField.text.length <= 0 || self.valueField.text.length <= 0 || self.detailView.text.length <= 0 || self.mainImageArray.count <= 0 || self.detailImageArray.count <= 0) {
        self.button.userInteractionEnabled = NO;
        [HttpManager showNoteMsg:@"请把信息补充完整"];
    }
    self.button.userInteractionEnabled = YES;
    [self uploadPics];
}

-(void)uploadPics
{
    WeakObj(self);
    [HttpManager uploadImageArr:self.detailImageArray success:^(id successResponse) {
        
        selfWeak.detailUrlArray = successResponse;
        [HttpManager uploadImageArr:selfWeak.mainImageArray success:^(id successResponse) {
            selfWeak.mainUrlArray = successResponse;
            [selfWeak requestdata];
        }];
    }];
}

-(void)requestdata
{
    if (self.detailUrlArray.count <= 0) {
        return;
    }
    
    if (self.mainUrlArray.count <= 0) {
        return;
    }
    
    NSString * main_pic = @""; /// [0], [1]
    for (NSString * urlStr in self.mainUrlArray) {
        if ([main_pic isEqualToString:@""]) {
            main_pic = urlStr;
        }else{
            main_pic = [NSString stringWithFormat:@"%@,%@",main_pic, urlStr]; /// [0], [1]
        }
    }
    
    NSString * detail_pic = @""; ///, [0], [1]
    for (NSString * urlStr in self.detailUrlArray) {
        if ([detail_pic isEqualToString:@""]) {
            detail_pic = urlStr;
        }else{
            detail_pic = [NSString stringWithFormat:@"%@,%@",detail_pic, urlStr]; /// [0], [1]
        }
    }
    NSString *url = [NSString stringWithFormat:@"%@app/shop_add_product",REQUESTHEADER];//添加商品
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setValue:[FPLoginAndRegisterTools getToken] forKey:@"token"];
    [dict setValue:self.shopId forKey:@"shop_id"];//店铺id
    [dict setValue:self.titleField.text forKey:@"design_name"];//产品名称
    [dict setValue:self.detailView.text forKey:@"design_des"];//产品描述
    [dict setValue:self.valueField.text forKey:@"price"];//价格 double
    [dict setValue:self.mainUrlArray[0] forKey:@"pic"];//设计产品展示图(就是上传主图的第一张)
    [dict setValue:main_pic forKey:@"main_pic"];//设计产品主图（两个url之间以逗号隔开）
    [dict setValue:detail_pic forKey:@"detail_pic"];//设计产品详情图（两个url之间以逗号隔开）
    if (_shopGoodsDetailModel) {
        [dict setValue:_shopGoodsDetailModel.Id forKey:@"pro_id"];
        url = [NSString stringWithFormat:@"%@app/shop_update_product",REQUESTHEADER];
    }
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [HttpManager hideWait];
            [HttpManager showNoteMsg:@"提交成功"];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:true];
            });
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
    
}

#pragma mark----- 选择弹出框
-(void)alterIconPortrait
{
    //弹出提示框
    __weak typeof(self)weakSelf = self;
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：拍摄
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openCamare];
    }]];
    //按钮：从手机相册选择
    [alert addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [weakSelf openAlbum];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 打开相册
-(void)openAlbum
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        
        if (status != PHAuthorizationStatusAuthorized) {
            return ;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // init Picker弹出图片选择界面
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            //隐藏空相册
            picker.showsEmptyAlbums = NO;
            //允许显示图片选中后的顺序
            picker.showsSelectionIndex = YES;
            //选择需要弹出的相册，一般我们只需要弹出相机胶卷和自定义相册即可
            picker.assetCollectionSubtypes = @[
                                               @(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
                                               @(PHAssetCollectionSubtypeAlbumRegular)
                                               ];
            // picker delegate
            picker.delegate = self;
            
            // present picker
            [self presentViewController:picker animated:YES completion:nil];
            
        });
    }];
    
}

#pragma mark - 打开相机
-(void)openCamare
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = YES;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark - UIImagePickerControllerDelegate  图片处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSLog(@"Picker returned successfully.");
    //    将选择的图片在imageView上显示
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
    if (self.isMainPic) {
        [self.mainImageArray addObject:image];
    }else{
        [self.detailImageArray addObject:image];
        indexPath=[NSIndexPath indexPathForRow:4 inSection:0];
    }
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    //处理完毕，回到个人信息页面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    NSLog(@"Picker was cancelled");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 设置图片最多选九张
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    NSInteger max = self.imageCount;
    if (picker.selectedAssets.count < max) return YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意" message:[NSString stringWithFormat:@"最多选择%ld张图片",(long)max] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    //一定要用picker 不能用self 因为当前显示在最上面的控制器是picker 而不是self
    [picker presentViewController:alert animated:YES completion:nil];
    
    return NO;
}

#pragma mark - 选择完毕的时候调用
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    //选择图片时的配置项 (如果不写配置项 会导致请求的图片尺寸出现问题)
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    //遍历图片选择的图片显示成九宫格样式
    for (NSInteger i = 0; i < assets.count; i ++) {
        PHAsset *asset = assets[i];
        CGFloat scale = UIScreen.mainScreen.scale;
        CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
        
        //请求图片 (需要先用图片管理员请求图片数据 请求完成后 在block里添加图片)
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            WeakObj(self);

            if (selfWeak.isMainPic) {
                [selfWeak.mainImageArray addObject:result];
                if (i == assets.count - 1) {
                    [self.tableView reloadData];
                }
            }else{
                [selfWeak.detailImageArray addObject:result];
                if (i == assets.count - 1) {
                    [self.tableView reloadData];
                }
            }
        }];
    }
}

/** 移除某一张照片*/
- (void)removeImage:(UIButton *)button
{
    [self showAlert:button];
    
}

- (void)showAlert:(UIButton *)button
{
    WeakObj(self);
    //显示提示框
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil  message:@"删除已选择的图片"  preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault   handler:^(UIAlertAction * action) {
        //响应事件
        if ((button.tag - 3000) < 0) {
            [selfWeak.mainImageArray removeObjectAtIndex:button.tag - 2000];
            [selfWeak reload];
        }else{
            [selfWeak.detailImageArray removeObjectAtIndex:button.tag - 3000];
            [selfWeak reloadDetail];
        }
        
        NSLog(@"action = %@", action);
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel   handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
        
    }];
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

/** 重新加载照片*/
- (void)reload
{
    /** 刷新*/
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

/** 重新加载照片*/
- (void)reloadDetail
{
    /** 刷新*/
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:4 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *noteArray = @[@"商品名称：",@"商品价格：",@"商品描述：",@"商品主图：(仅支持jpg/png格式图片）最多选择9张",@"商品详情图：(仅支持jpg/png格式图片）最多选择9张",@""];
    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375((SCREEN_WIDTH - 26)), ScreenX375(45))];
    noteLabel.text = noteArray[indexPath.row];
    noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
    noteLabel.font = Kfont(14);
    
    if (indexPath.row == 0) {
        static NSString *cellId = @"nameCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        [cell addSubview:noteLabel];
        
        if (!self.titleField) {
            self.titleField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(45))];
            self.titleField.font = Kfont(14);
            self.titleField.delegate = self;
            self.titleField.placeholder = @"请输入商品名称";
            if (_shopGoodsDetailModel) {
                self.titleField.text = _shopGoodsDetailModel.design_name;
            }
        }
        [cell addSubview:self.titleField];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(45) - 0.5, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = LineColor;
        [cell addSubview:line];
        
        return cell;
    }else if (indexPath.row == 1) {
        static NSString *cellId = @"valueCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        [cell addSubview:noteLabel];
        
        if (!self.valueField) {
            self.valueField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(45))];
            self.valueField.delegate = self;
            self.valueField.font = Kfont(14);
            self.valueField.placeholder = @"请输入商品价格";
            self.valueField.textColor = ThemeColor;
            if (self.shopGoodsDetailModel) {
                self.valueField.text = _shopGoodsDetailModel.price;
            }
        }
        [cell addSubview:self.valueField];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(45) - 0.5, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = LineColor;
        [cell addSubview:line];
        
        return cell;
    }else if (indexPath.row == 2) {
        static NSString *cellId = @"detailCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        
        [cell addSubview:noteLabel];
        
        if (!self.detailView) {
            self.detailView = [[UITextView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(45), SCREEN_WIDTH - ScreenX375(26), ScreenX375(112))];
            self.detailView.textColor = REXADECIMALCOLOR(@"#c2c2c2");
            self.detailView.font = Kfont(12);
            self.detailView.delegate = self;
            self.detailView.layer.cornerRadius = 5;
            self.detailView.clipsToBounds = YES;
            self.detailView.layer.borderWidth = 1;
            self.detailView.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
            self.detailView.text = @"请输入商品描述";
            if (self.shopGoodsDetailModel) {
                self.detailView.text = self.shopGoodsDetailModel.design_des;
                self.detailView.textColor = REXADECIMALCOLOR(@"#222222");
            }
        }
        [cell addSubview:self.detailView];
        
        return cell;
    }else if (indexPath.row == 3) { // 商品主图
        static NSString *cellId = @"mianImgCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        [cell addSubview:noteLabel];
        
        CGFloat margin = (SCREEN_WIDTH - ScreenX375(26) - ScreenX375(330)) / 2;
        for (int i = 0; i < self.mainImageArray.count; i++) {
            
            CGFloat x = i % 3 * (ScreenX375(110) + margin) + ScreenX375(13);
            CGFloat y = i / 3 * ScreenX375(120) + ScreenX375(45);
            UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, ScreenX375(110), ScreenX375(110))];
            imageV.image = self.mainImageArray[i];
            imageV.userInteractionEnabled = YES;
            imageV.tag = 999;
            [cell addSubview:imageV];
            
            /** 为图片添加一个右上角的删除按钮*/
            UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            CGFloat removeX = ScreenX375(110) - ScreenX375(20);
            CGFloat removeW = ScreenX375(24);
            removeBtn.frame = CGRectMake(removeX, -12, removeW, removeW);
            [removeBtn setImage:[UIImage imageNamed:@"案例删除"] forState:UIControlStateNormal];
            [removeBtn addTarget:self action:@selector(removeImage:) forControlEvents:UIControlEventTouchUpInside];
            removeBtn.tag = i + 2000;
            [imageV addSubview:removeBtn];
        }

        if (self.mainImageArray.count != 9) {
            AddImgButton *addBtn = [[AddImgButton alloc] initWithFrame:CGRectMake(self.mainImageArray.count % 3 * (ScreenX375(110) + margin) + ScreenX375(13), self.mainImageArray.count / 3 * ScreenX375(120) + ScreenX375(45), ScreenX375(110), ScreenX375(110))];
            
            [addBtn addTarget:self action:@selector(mainPicAdd) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:addBtn];
        }
        return cell;
    }else if (indexPath.row == 4) { // 商品详情图
        static NSString *cellId = @"detailImgCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        [cell addSubview:noteLabel];
       
        CGFloat margin = (SCREEN_WIDTH - ScreenX375(26) - ScreenX375(330)) / 2;
        for (int i = 0; i < self.detailImageArray.count; i++) {
            
            CGFloat x = i % 3 * (ScreenX375(110) + margin) + ScreenX375(13);
            CGFloat y = i / 3 * ScreenX375(120) + ScreenX375(45);
            UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, ScreenX375(110), ScreenX375(110))];
            imageV.image = self.detailImageArray[i];
            imageV.userInteractionEnabled = YES;
            [cell addSubview:imageV];
            
            /** 为图片添加一个右上角的删除按钮*/
            UIButton *removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            CGFloat removeX = ScreenX375(110) - ScreenX375(20);
            CGFloat removeW = ScreenX375(24);
            removeBtn.frame = CGRectMake(removeX, -12, removeW, removeW);
            [removeBtn setImage:[UIImage imageNamed:@"案例删除"] forState:UIControlStateNormal];
            [removeBtn addTarget:self action:@selector(removeImage:) forControlEvents:UIControlEventTouchUpInside];
            removeBtn.tag = i + 3000;
            [imageV addSubview:removeBtn];
        }
        
        if (self.detailImageArray.count != 9) {
            AddImgButton *addBtn = [[AddImgButton alloc] initWithFrame:CGRectMake(self.detailImageArray.count % 3 * (ScreenX375(110) + margin) + ScreenX375(13), self.detailImageArray.count / 3 * ScreenX375(120) + ScreenX375(45), ScreenX375(110), ScreenX375(110))];
            [addBtn addTarget:self action:@selector(detailPicAdd) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:addBtn];
        }
        return cell;
    }else {
        static NSString *cellId = @"operateCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        
        self.button = [[ThemeButton alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(60), SCREEN_WIDTH - ScreenX375(26), ScreenX375(44))];
        [self.button setTitle:@"确认发布" forState:UIControlStateNormal];
        [self.button addTarget:self action:@selector(surePublic) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:self.button];
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 1) {
        return ScreenX375(45);
    }else if (indexPath.row == 2) {
        return ScreenX375(157);
    }else if (indexPath.row == 3) {
        return ScreenX375(45) + (self.mainImageArray.count / 3 + 1) * ScreenX375(110) + self.mainImageArray.count / 3 * ScreenX375(10);
    }else if (indexPath.row == 4) {
        return ScreenX375(45) + (self.detailImageArray.count / 3 + 1) * ScreenX375(110) + self.detailImageArray.count / 3 * ScreenX375(10);
    }else {
        return ScreenX375(132);
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return NO;
}

-(void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请输入商品描述)"]) {
        textView.textColor = [UIColor blackColor];
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length < 1) {
        textView.textColor = REXADECIMALCOLOR(@"#999999");
        textView.text = @"请输入商品描述";
    }
}

@end
